package com.hdax.controller;

import com.hdax.entity.*;
import com.hdax.service.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 考勤控制器
 *
 * @author Aizen
 * @date 2022/05/16
 */
@Controller
@RequestMapping("/attendance")
public class AttendanceController {

    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @Autowired
    private LeaveService leaveService;

    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/index")
    public String list(Model model) {
        model.addAttribute("attdate",attendanceService.CountMoney());

        model.addAttribute("attemp",employeeInfoService.selectAll());
        return "attendance/AttendanceProfiles";
    }

    @PostMapping(path = "/list")
    @ResponseBody
    public Map<String,Object> list(@RequestParam("page")int page, @RequestParam("limit")int limit, @Param("attendance") Attendance attendance,int id){
        //获取当前登录的人的id,在部门表中查询是否是项目经理
        List<Department> dlist=departmentService.listAll(id);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "");
        //获取本月时间
        Calendar cal=Calendar.getInstance();
        // 当前年
        int year = cal.get(Calendar.YEAR);
        // 当前月
        int month = cal.get(Calendar.MONTH) + 1;
        //获取今天几号
        int day = cal.get(Calendar.DAY_OF_MONTH);
        //获取一号
        String yih=null;
        String sj=null;
        if (month<10){
            String yue="0"+month;
            if (day<10){
                String jin="0"+day;
                sj=year+"-"+yue+"-"+jin;
            }else{
                day=day;
                sj=year+"-"+yue+"-"+day;
            }
            yih=year+"-"+yue+"-00";
        }else{
            month=month;
            if (day<10){
                String jin="0"+day;
                sj=year+"-"+month+"-"+jin;
            }else{
                day=day;
                sj=year+"-"+month+"-"+day;
            }
            yih=year+"-"+month+"-00";
        }


        int daijian=day-1;
        for (int i = 0; i < day; i++) {
            //昨天几号
            String date=null;
            if (month<10){
                String xinyue="0"+month;
                if(daijian<10){
                    String xinjian="0"+daijian;
                    date=year+"-"+xinyue+"-"+xinjian;
                }else{
                    date=year+"-"+xinyue+"-"+daijian;
                }

            }else{
                month=month;
                if(daijian<10){
                    String xinjian="0"+daijian;
                    date=year+"-"+month+"-"+xinjian;
                }else{
                    date=year+"-"+month+"-"+daijian;
                }

            }
            if (date.equals(yih)){
                break;
            }else{
                //查询所有员工
                List<EmployeeInfo> es=employeeInfoService.selectAll();
                for (int j = 0; j < es.size(); j++) {
                    //获取员工id
                    int eid=es.get(j).getId();
                    Attendance at= attendanceService.setexist(eid,date,sj);
                    if (at==null){
                        String jaisfm=date+" 06:06:06";
                        attendanceService.setsan(eid,jaisfm);
                    }else{
                        continue;
                    }
                }
                sj=date;
                daijian--;
            }
        }
        if (id!=1){
            attendance.setEmployeeid(id);
        }
        if (attendance.getEmployeeid()!=null || attendance.getDakadateone()!=null){
            List<Attendance> attendanceList=attendanceService.findAll((page-1)*limit,limit,attendance);
            //查询总条数(该名称下)
            map.put("count", attendanceService.countByAtt(attendance));
            map.put("data", attendanceList);
        }else{
            if (page-1!=0 || limit!=0){
                List<Attendance> attendanceList=attendanceService.findAll((page-1)*limit,limit,attendance);
                int count=attendanceService.count(attendance);
                map.put("count", count);
                map.put("data", attendanceList);
            }else if (dlist.size()==0){
                attendance.setEmployeeid(id);
                List<Attendance> attendanceList=attendanceService.findAll((page-1)*limit,limit,attendance);
                //查询总条数(该名称下)
                map.put("count", attendanceService.countByAtt(attendance));
                map.put("data", attendanceList);
            }else{
                List<Attendance> konglist=new ArrayList<>();
                int count=0;
                for (int i = 0; i < dlist.size(); i++) {
                    //获取部门的编号
                    int did= dlist.get(i).getId();
                    List<EmployeeInfo> elist=employeeInfoService.emplist(did);
                    for (int j = 0; j < elist.size(); j++) {
                        //获取员工的编号
                        int empid=elist.get(j).getId();
                        List<Attendance> attendanceList=attendanceService.findByeid(empid);
                        for (int k = 0; k < attendanceList.size(); k++) {
                            //获取考勤表id
                            int leaid=attendanceList.get(k).getId();
                            Attendance att=attendanceService.selectByid(leaid);
                            konglist.add(att);
                            count++;
                        }
                    }
                }

                //查询总条数(该名称下)
                map.put("count", count);
                map.put("data", konglist);
            }
        }
        return map;
    }

    /**
     * 上班打卡
     * @param empid
     * @return
     */
    @PostMapping(path = "sdaka")
    @ResponseBody
    public Map<String,Object> cpdelete(Integer empid){

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("code", 0);
        Attendance attendance=new Attendance();
        attendance.setEmployeeid(empid);
        //判断当前是否打卡
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        attendance.setShangbantime(formatter.format(date));
        int dangqain=attendanceService.selectByDaka(attendance);
        if (dangqain>0){
            map.put("msg","您今天已打卡");
            map.put("data","success");
        }else{
            int result=attendanceService.insertByshang(attendance);
            if(result>0) {
                map.put("msg","打卡成功");
                map.put("data","success");
            }else {
                map.put("msg","打卡失败");
                map.put("data","fail");
            }
        }
        return map;
    }

    /**
     * 下班打卡
     * @param empid
     * @return
     */
    @PostMapping(path = "xdaka")
    @ResponseBody
    public Map<String,Object> xdaka(Integer empid){

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("code", 0);

        //判断是否以及下班打卡
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        Attendance attendance=new Attendance();
        attendance.setDakadateone(formatter.format(date));
        attendance.setEmployeeid(empid);

        Attendance a =attendanceService.ac(attendance);
        String xiabandate=a.getXiabantime();
        if (xiabandate==null || xiabandate==""){
            int result=attendanceService.updateByxia(attendance);
            if(result>0) {
                map.put("msg","打卡成功");
                map.put("data","success");
            }else {
                map.put("msg","打卡失败");
                map.put("data","fail");
            }
        }else{
            map.put("msg","您今天已打卡");
            map.put("data","success");
        }
        return map;
    }

    @GetMapping(path = "/qleave")
    public ModelAndView qleave(int id){
        ModelAndView mav=new ModelAndView("attendance/Leave");
        EmployeeInfo employeeInfo=employeeInfoService.findEmployeeInfoById(id);
        mav.addObject("einfo",employeeInfo);
        return mav;
    }

    @PostMapping(path = "qleave")
    @ResponseBody
    @Transactional(rollbackFor=Exception.class)
    public Map<String,Object> qleave(Leave leave){

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("code", 0);
        int result =leaveService.insertByid(leave);
        if(result>0) {
            map.put("msg","提交完成");
            map.put("data","success");
        }else {
            map.put("msg","提交失败");
            map.put("data","fail");
        }
        return map;
    }

    public static List<String> getBetDate(String startTime,String endTime){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //声明保存的日期集合
        List<String> list=new ArrayList<String>();

        try {
            //转换类型
            Date startDate=sdf.parse(startTime);
            Date endDate=sdf.parse(endTime);
            //日期比较
            Calendar calendar=Calendar.getInstance();
            while (startDate.getTime()<=endDate.getTime()){
                //把日期添加到集合中
                list.add(sdf.format(startDate));
                //设置日期
                calendar.setTime(startDate);
                //把日期加1天
                calendar.add(Calendar.DATE,1);
                //获取加完之后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }


    @GetMapping(path = "/approval")
    public ModelAndView approval(int id){
        ModelAndView mav=new ModelAndView("attendance/Approval");
        //根据id查询部门经理
        List<Department> departmentList= departmentService.listAll(id);
        //定义的空表,存放查询出的内容
        List<Leave> listin=new ArrayList<>();
        //循环该id下的部门经理
        for (int i = 0; i < departmentList.size(); i++) {
            //获取部门id,查询该部门下的人请假条数
            List<Leave> leaves= leaveService.findByRoleid(departmentList.get(i).getId());
            for (int j = 0; j < leaves.size(); j++) {
                //获取请假表中的编号
                int lid= leaves.get(j).getId();
                String name =leaves.get(j).getEmpname().getEmpName();
                String statename=leaves.get(j).getStatename().getStateName();
               Leave leave= leaveService.findBylid(lid);
               leave.setEmpbyname(name);
               leave.setStatebyname(statename);
               //查询后放入空表中
               listin.add(leave);
            }
        }
        System.out.println(listin);
        mav.addObject("listin",listin);
        return mav;
    }

    @PostMapping(path = "approval")
    @ResponseBody
    @Transactional(rollbackFor=Exception.class)
    public Map<String,Object> qapproval(Leave leave){

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("code", 0);
        //开始时间
        String startStr=leave.getLeavedate1();
        //结束时间
        String endStr=leave.getLeavedate2();
        List<String> list=getBetDate(startStr,endStr);
        //获取当前时间
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        String end=formatter.format(date);
        leave.setLeavestate(13);
        int result =leaveService.updateByid(leave);
        for (int i = 0; i < list.size(); i++) {
            String daka= list.get(i);
            attendanceService.insetByDate(leave.getEmpid(),daka,end);
        }
        if(result>0) {
            map.put("msg","提交完成");
            map.put("data","success");
        }else {
            map.put("msg","提交失败");
            map.put("data","fail");
        }
        return map;
    }
}
